package com.hengxinguotong.hxgtwygsp.net;



import com.hengxinguotong.hxgtwygsp.BuildConfig;

import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;

/**
 * Created by pc on 2018/1/16.
 */

public class ClientFactory
{
    public static OkHttpClient create(String urlStr)
    {
        OkHttpClient.Builder builder = null;
        try
        {
            if (urlStr.startsWith("https"))
            {
                SSLContext sslContext = getSSLContext();
                builder = new OkHttpClient.Builder()
                        .sslSocketFactory(sslContext.getSocketFactory())
                        .hostnameVerifier(getVerifier());
            } else
            {
                builder = new OkHttpClient.Builder();
            }
            builder.connectTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS);
            if (BuildConfig.DEBUG)
            {
                LogInterceptor logInterceptor = new LogInterceptor();
                builder.addInterceptor(logInterceptor);
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return builder != null ? builder.build() : null;
    }

    public static SSLContext getSSLContext()
    {
        X509TrustManager xtm = new X509TrustManager()
        {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
            {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType)
            {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers()
            {
                X509Certificate[] x509Certificates = new X509Certificate[0];
                return x509Certificates;
            }
        };
        SSLContext sslContext = null;
        try
        {
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return sslContext;
    }

    public static HostnameVerifier getVerifier()
    {
        return new HostnameVerifier()
        {
            @Override
            public boolean verify(String hostname, SSLSession session)
            {
                return true;
            }
        };
    }
}
